from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.conf import settings
from .models import Software, Version
import os


@admin.register(Software)
class SoftwareAdmin(admin.ModelAdmin):
    list_display = ['name', 'created_at', 'updated_at']
    search_fields = ['name']


@admin.register(Version)
class VersionAdmin(admin.ModelAdmin):
    list_display = ['software', 'version_number', 'status', 'is_force_update', 
                   'release_date', 'file_size_display', 'download_link']
    list_filter = ['status', 'is_force_update', 'software']
    search_fields = ['version_number', 'software__name']
    date_hierarchy = 'release_date'
    readonly_fields = ['file_size', 'file_size_display', 'download_link']

    def file_size_display(self, obj):
        """显示人类可读的文件大小"""
        if obj.file_size:
            # 转换文件大小为易读格式
            for unit in ['B', 'KB', 'MB', 'GB']:
                if obj.file_size < 1024:
                    return f"{obj.file_size:.2f} {unit}"
                obj.file_size /= 1024
            return f"{obj.file_size:.2f} TB"
        return "-"
    file_size_display.short_description = "文件大小"

    def download_link(self, obj):
        """显示下载链接"""
        if obj.version_file:
            file_url = obj.version_file.url
            filename = os.path.basename(obj.version_file.name)
            return format_html('<a href="{}" target="_blank">{}</a>', file_url, filename)
        elif obj.download_url:
            return format_html('<a href="{}" target="_blank">外部下载</a>', obj.download_url)
        return "-"
    download_link.short_description = "下载链接" 